import { renderWelcomeData } from './welcomeOptionItem';
import { ElProgress } from 'element-plus';

export const taskType = {
    IMPORT: 1, // 导入
    EXPORT: 2, // 导出
    TRANSFER: 3, // 转移
    DELETE: 4, // 删除
    UPDATE: 5, // 更新
    SUBTASK: 6 // 子任务
};

// 表单数据属性名
export const ListAttributeName = new Map([
    [taskType.IMPORT, 'import_data'],
    [taskType.EXPORT, 'export_data'],
    [taskType.TRANSFER, 'transfer_data'],
    [taskType.DELETE, 'action_data'],
    [taskType.UPDATE, 'update_data'],
    [taskType.SUBTASK, 'subtask_data']
]);

// 列表标题名称
export const ListTitleName = new Map([
    [taskType.IMPORT, '失败明细'],
    [taskType.EXPORT, '文件下载明细'],
    [taskType.TRANSFER, '转移明细'],
    [taskType.DELETE, '删除失败明细'],
    [taskType.UPDATE, '更新明细'],
    [taskType.SUBTASK, '子任务明细']
]);

// 渲染文本
export const renderText = (text: any) => {
    return [undefined, null, ''].includes(text) ? '-' : text;
};

// 渲染源数据
const renderData = (cellValue: any) => {
    if (!cellValue) return '-';
    let data = cellValue;
    try {
        const datalist = JSON.parse(cellValue);
        data = Array.isArray(datalist) ? datalist.join(',') : cellValue;
    } catch (err) {
        data = renderText(cellValue);
    }
    return (
        <el-tooltip popper-class="auto_width auto_height" effect="light" content={data} placement="top">
            <div class="zw-text-ellipsis2">{data}</div>
        </el-tooltip>
    );
};

// 状态颜色
const StatusTextColorOption = {
    成功: ['#32D1AD', '#E8FAF6'],
    失败: ['#666666', '#EAEAEA']
};
const renderStatus = (cellValue: any) => {
    return (
        <div
            class="status_text"
            style={{
                '--status-bgcolor': StatusTextColorOption[cellValue]?.[1],
                '--status-color': StatusTextColorOption[cellValue]?.[0]
            }}>
            {cellValue}
        </div>
    );
};

// 更新前后数据
const StatusPointColorOption = {
    未开始: '#D8D8D8',
    进行中: '#2FB6E4',
    已结束: '#FF6B00',
    提前结束: '#FF6B00'
};
const renderStatusPoint = (cellValue: any) => {
    return (
        <div
            class="status_point"
            style={{
                '--status-bgcolor': StatusPointColorOption[cellValue]
            }}>
            {cellValue}
        </div>
    );
};

const WAIT = 1; // 等待|未开始
const INPROGRESS = 2; // 进行中
const COMPLETED = 3; // 已完成
const ANOMALY = 4; // 异常
const CANCELLED = 5; // 已取消
const INEFFECTIVE = 6; // 已失效
const FAIL = 7; // 失败

// 状态颜色
const StatusColorOption = {
    [WAIT]: '#FFD500',
    [INPROGRESS]: '#2FB6E4',
    [ANOMALY]: '#F14144',
    [CANCELLED]: '#D8D8D8',
    [COMPLETED]: '#32D1AD',
    [INEFFECTIVE]: '#D8D8D8',
    [FAIL]: '#F14144'
};

// 进度条颜色
const ProgressColor = {
    [WAIT]: '#FFD500',
    [INPROGRESS]: '#5AB8F9',
    [COMPLETED]: '#32D1AD',
    [ANOMALY]: '#F14144',
    [INEFFECTIVE]: '#32D1AD',
    [FAIL]: '#F14144'
};

const renderProgress = (cellValue: any, row: any) => {
    const progressNum = (+row.line_total_success || 0) + (+row.line_total_fail || 0);
    const percentage = progressNum ? Number(Math.floor((progressNum / (+row.line_total || 0)) * 100)) : 0;
    const isOver = [COMPLETED, INEFFECTIVE].includes(row.task_state);
    return row.task_state === CANCELLED ? (
        <div></div>
    ) : (
        <div>
            {
                // 已完成 || 已失效
                isOver ? (
                    <>
                        <span class="table_total_num">{`总数${row.line_total}`}</span>
                        <span class="table_sussess_num">{`成功${row.line_total_success}`}</span>
                        <span class="table_fail_num">{`失败${row.line_total_fail}`}</span>
                    </>
                ) : // 失败 异常
                row.task_state === FAIL || row.task_state === ANOMALY ? (
                    <>
                        <span class="table_total_num">
                            {' '}
                            {progressNum} / {row.line_total || 0}{' '}
                        </span>
                        <span class="table_sussess_num">{`成功${row.line_total_success}`}</span>
                        <span class="table_fail_num">{`失败${row.line_total_fail}`}</span>
                    </>
                ) : (
                    // 非异常
                    <span class="table_total_num">
                        {' '}
                        {progressNum} / {row.line_total || 0}{' '}
                    </span>
                )
            }
            <ElProgress
                stroke-width={8}
                color={ProgressColor[row.task_state]}
                percentage={Number.isFinite(percentage) && row.line_total != 0 ? percentage : 100}
                status={isOver ? 'success' : row.task_state === ANOMALY ? 'warning' : undefined}
            />
        </div>
    );
};

const renderSubtaskState = (cellValue: any, row: any) => {
    return (
        <div
            class="subtask_status_point"
            style={{
                '--status-bgcolor': StatusColorOption[row.task_state] ?? '#D8D8D8'
            }}>
            {row.task_state_name}
        </div>
    );
};

// 列配置项的策略
const columnOption = {
    // 导入
    import_data: [
        ['line_num', '行号'],
        ['err', '错误说明', 180],
        ['data', '源数据', 200, renderData]
    ],
    // 导出
    export_data: [
        ['id', '编号'],
        ['title', '文件名', 220],
        ['created_uid_name', '下载员工'],
        ['created_at', '下载时间', 200]
    ],
    // 删除
    action_data: [
        ['id', '编号'],
        ['error_msg', '错误说明', 180],
        ['data', '源数据', 220, renderData]
    ],
    // 更新
    update_data: {
        normal: [
            ['id', '编号'],
            ['title', '数据标识', 120],
            ['before', '更新前', 160, renderStatusPoint],
            ['after', '更新后', 160, renderStatusPoint],
            ['execute_state_name', '状态', 120, renderStatus],
            ['error_msg', '失败原因']
        ],
        // 标签任务类型
        tag: [
            ['id', '编号'],
            ['title', '数据标识', 180],
            ['update_content', '更新标签', 200],
            ['execute_state_name', '状态', 120, renderStatus],
            ['error_msg', '失败原因']
        ],
        // 欢迎语任务类型 module_type-16
        welcome: [
            ['id', '编号'],
            ['title', '数据标识', 160],
            ['before', '更新前', 260, renderWelcomeData],
            ['after', '更新后', 260, renderWelcomeData],
            ['execute_state_name', '状态', 120, renderStatus],
            ['error_msg', '失败原因']
        ]
    },
    // 转移
    transfer_data: [
        ['id', '编号'],
        ['title', '数据标识', 120],
        ['before', '更新前', 160],
        ['after', '更新后', 160],
        ['execute_state_name', '状态', 120, renderStatus],
        ['err_msg', '失败原因']
    ],
    // 子任务明细
    subtask_data: [
        ['id', '子任务编号', 160],
        ['task_name', '子任务名称', 200, renderData],
        ['created_uid', '子任务进度', 220, renderProgress],
        ['task_state_name', '状态', 120, renderSubtaskState],
        ['finish_time', '完成时间', 200]
    ]
};

// 获取列配置项
export function tableColumnOption(optionType: OptionType) {
    const option = getColumnOption(optionType);
    return option.map((item: [prop: string, label: string, minWidth?: number, renderData?: Function]) => {
        return createColumnOption(...item);
    });
}

// 生成列配置项
const createColumnOption = (prop: string, label: string, minWidth?: number, renderData?: Function) => {
    const renderSlot = ({ row }: any) => {
        if (!row[prop]) return '-';
        return renderData?.(row[prop], row);
    };

    return {
        prop,
        label,
        showOverflowTooltip: true,
        minWidth,
        render: renderData ? renderSlot : undefined
    };
};

// 获取配置的列根据详情的类型
const getColumnOption = ({ type, is_tag, module_type }: OptionType) => {
    const columnOptionByType = columnOption[ListAttributeName.get(type) || ''] || [];
    return Array.isArray(columnOptionByType)
        ? columnOptionByType
        : is_tag
        ? columnOptionByType.tag
        : module_type == 16
        ? columnOptionByType.welcome
        : columnOptionByType.normal;
};

interface OptionType {
    type: number;
    is_tag?: boolean;
    is_job?: boolean;
    module_type?: string | number;
}
